<template>
  <div class="app-container">
    <el-form :inline="true" :model="queryParams" class="filter-form">
      <el-form-item label="日期：">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 260px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset" type="text">清空筛选条件</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="regionName" label="区县" align="center" />
      <el-table-column prop="maintenanceCount" label="维修订单" align="center">
        <template #default="scope">
          <span class="order-link" @click="goToOrderList('repair', scope.row)">{{ scope.row.maintenanceCount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="careCount" label="保养订单" align="center">
        <template #default="scope">
          <span class="order-link" @click="goToOrderList('maintain', scope.row)">{{ scope.row.careCount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="washCount" label="洗车订单" align="center">
        <template #default="scope">
          <span class="order-link" @click="goToOrderList('wash', scope.row)">{{ scope.row.washCount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="totalCount" label="总计" align="center" />
    </el-table>
  </div>
</template>

<script setup name="OrderStatistic">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getOrderStatisticsByRegion } from '@/api/order/order'

const queryParams = ref({
  dateRange: []
})
const tableData = ref([])
const router = useRouter()

function fetchData() {
  const [startTime, endTime] = queryParams.value.dateRange || []
  getOrderStatisticsByRegion({ startTime, endTime }).then(res => {
    if (res && res.code === 200) {
      tableData.value = res.data || []
    }
  })
}

function handleSearch() {
  fetchData()
}

function handleReset() {
  queryParams.value.dateRange = []
  fetchData()
}

function goToOrderList(type, row) {
  // type: repair/care/wash
  // 跳转到对应订单列表页面，并带上区县和时间参数
  let path = ''
  if (type === 'repair') path = '/order/repair'
  else if (type === 'maintain') path = '/order/maintain'
  else if (type === 'wash') path = '/order/wash'
  router.push({
    path: path
  })
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.app-container {
  padding: 24px;
}
.filter-form {
  margin-bottom: 16px;
}
.order-link {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
}
</style>